<template>
  <div :class="{ 'fullscreen-editor': isFullscreen }">
    <!-- 编辑器容器 -->
    <div ref="editorWrapper" class="editor-wrapper">
      <!-- Quill 编辑器容器，工具栏会由 Quill 自动插入到此处 -->
      <div ref="editor" :style="{ height: editorHeight }"></div>

      <!-- 字数统计 -->
      <div v-if="showWordCount" class="word-counter">
        {{ currentWordCount }} / {{ maxLength }} 字
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';
import ImageResize from 'quill-image-resize-module-react';

// 注册图片大小调整模块
Quill.register('modules/imageResize', ImageResize);

const props = defineProps({
  modelValue: {
    type: [String, Object],
    default: '',
  },
  height: {
    type: String,
    default: '300px',
  },
  contentType: {
    type: String,
    default: 'html',
    validator: (value) => ['html', 'delta'].includes(value),
  },
  // 关键：最后一排从 ['image'] 改成 ['image', 'fullscreen']
  toolbar: {
    type: [Array, Boolean],
    default: () => [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ header: [1, 2, 3, false] }],
      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ script: 'sub' }, { script: 'super' }],
      [{ indent: '-1' }, { indent: '+1' }],
      [{ direction: 'rtl' }],
      [{ size: ['small', false, 'large', 'huge'] }],
      [{ color: [] }],
      [{ font: [] }],
      [{ align: [] }],
      ['clean'],
      ['image', 'fullscreen'],
    ],
  },
  maxLength: Number,
  allowFullscreen: {
    type: Boolean,
    default: true,
  },
  uploadImage: {
    type: Function,
    default: null,
  },
  placeholder: {
    type: String,
    default: '请输入内容...',
  },
});

const emit = defineEmits([
  'update:modelValue',
  'exceed-limit',
  'image-uploaded',
  'fullscreen-change',
]);

// 响应式状态
const editor = ref(null);
const quillInstance = ref(null);
const editorHeight = ref(props.height);
const isFullscreen = ref(false);
const currentWordCount = ref(0);
const showWordCount = ref(!!props.maxLength);

// 初始化编辑器
const initEditor = async () => {
  // —— 第①步：注入“fullscreen”图标 ——
  const icons = Quill.import('ui/icons');
  icons['fullscreen'] = `
    <svg viewBox="0 0 18 18">
      <polygon class="ql-fill" points="3 3 3 7 1 7 1 1 7 1 7 3 3 3"></polygon>
      <polygon class="ql-fill" points="15 3 11 3 11 1 17 1 17 7 15 7 15 3"></polygon>
      <polygon class="ql-fill" points="3 15 3 11 1 11 1 17 7 17 7 15 3 15"></polygon>
      <polygon class="ql-fill" points="15 15 15 11 17 11 17 17 11 17 11 15 15 15"></polygon>
    </svg>
  `;

  // —— 第②步：创建 Quill 实例 ——
  quillInstance.value = new Quill(editor.value, {
    theme: 'snow',
    modules: {
      toolbar: props.toolbar,
      imageResize: {
        displaySize: true,
        modules: ['Resize', 'DisplaySize'],
      },
    },
    placeholder: props.placeholder,
  });

  // —— 第③步：注册 Quill toolbar 里的 fullscreen 按钮点击 ——
  const toolbarModule = quillInstance.value.getModule('toolbar');
  // 用 Quill 自带的 addHandler
  toolbarModule.addHandler('fullscreen', toggleFullscreen);

  // **额外**：保证 icon 渲染后仍然能绑定，手动找一下 DOM 元素再加一次点击
  // 要等下一次 DOM 更新周期，才能拿到真正插入进来的 .ql-fullscreen 按钮
  await nextTick();
  // 通过 editorWrapper 查找 .ql-fullscreen
  const wrapperEl = editor.value.parentElement; // editorWrapper
  const btn = wrapperEl.querySelector('.ql-fullscreen');
  if (btn) {
    btn.onclick = () => {
      toggleFullscreen();
    };
  }

  initContent();
  registerImageHandler();
  setupEventListeners();
};

// 初始化内容（HTML 或 Delta）
const initContent = () => {
  if (!props.modelValue) return;
  try {
    if (props.contentType === 'delta') {
      quillInstance.value.setContents(props.modelValue);
    } else {
      quillInstance.value.root.innerHTML = props.modelValue;
    }
  } catch (error) {
    console.error('内容初始化失败:', error);
    quillInstance.value.setText('');
  }
};

// 图片上传逻辑
const registerImageHandler = () => {
  if (!props.uploadImage) return;
  const toolbar = quillInstance.value.getModule('toolbar');
  toolbar.addHandler('image', () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = async () => {
      const file = input.files[0];
      if (!file) return;
      try {
        const url = await props.uploadImage(file);
        const range = quillInstance.value.getSelection();
        quillInstance.value.insertEmbed(range.index, 'image', url);
        emit('image-uploaded', url);
      } catch (error) {
        console.error('图片上传失败:', error);
      }
    };
    input.click();
  });
};

// 文本变化监听
const setupEventListeners = () => {
  const textChangeHandler = () => {
    updateContent();
    updateWordCount();
  };
  quillInstance.value.on('text-change', textChangeHandler);
};

// 同步内容到外部
const updateContent = () => {
  let content;
  try {
    content =
      props.contentType === 'delta'
        ? quillInstance.value.getContents()
        : quillInstance.value.root.innerHTML;
  } catch (error) {
    console.error('内容获取失败:', error);
    return;
  }
  if (content !== props.modelValue) {
    emit('update:modelValue', content);
  }
};

// 字数统计
const updateWordCount = () => {
  const text = quillInstance.value.getText().trim();
  currentWordCount.value = text.length;
  if (props.maxLength && text.length > props.maxLength) {
    emit('exceed-limit', text.length);
  }
};

// 全屏切换逻辑
const toggleFullscreen = () => {
  if (!props.allowFullscreen) return;
  isFullscreen.value = !isFullscreen.value;
  document.documentElement.style.overflow = isFullscreen.value ? 'hidden' : '';
  console.log('[toggleFullscreen] 当前 isFullscreen =', isFullscreen.value);

  if (isFullscreen.value) {
    // 进入全屏：让编辑器高度撑满（减留白 50px，可自行调整）
    editorHeight.value = `${window.innerHeight - 50}px`;
  } else {
    // 退出全屏：恢复到原来传进来的 props.height
    editorHeight.value = props.height;
  }
  emit('fullscreen-change', isFullscreen.value);
};

// 窗口尺寸变化时，如果在全屏状态，要重新计算高度
const handleResize = () => {
  if (isFullscreen.value) {
    editorHeight.value = `${window.innerHeight - 50}px`;
  }
};

// 监听生命周期与属性变化
onMounted(() => {
  initEditor();
  window.addEventListener('resize', handleResize);
});
onUnmounted(() => {
  if (quillInstance.value) {
    quillInstance.value.off('text-change');
  }
  window.removeEventListener('resize', handleResize);
});

// 当外部传入的 modelValue 变化时，同步到编辑器
watch(
  () => props.modelValue,
  (newVal) => {
    if (!quillInstance.value) return;
    const currentContent =
      props.contentType === 'delta'
        ? quillInstance.value.getContents()
        : quillInstance.value.root.innerHTML;
    if (currentContent !== newVal) {
      try {
        if (props.contentType === 'delta') {
          quillInstance.value.setContents(newVal);
        } else {
          quillInstance.value.root.innerHTML = newVal || '';
        }
      } catch (error) {
        console.error('内容更新失败:', error);
      }
    }
  }
);

// 当外部传入的 height 变化时，如果不在全屏，就同步更新 editorHeight
watch(
  () => props.height,
  (newHeight) => {
    if (!isFullscreen.value) {
      editorHeight.value = newHeight;
    }
  }
);

// 暴露内部方法
defineExpose({
  getEditor: () => quillInstance.value,
  getContent: () => {
    return props.contentType === 'delta'
      ? quillInstance.value?.getContents()
      : quillInstance.value?.root.innerHTML;
  },
  setContent: (content) => {
    if (quillInstance.value) {
      if (props.contentType === 'delta') {
        quillInstance.value.setContents(content);
      } else {
        quillInstance.value.root.innerHTML = content;
      }
    }
  },
  toggleFullscreen,
  clearContent: () => {
    quillInstance.value?.setText('');
  },
  insertText: (text) => {
    const range = quillInstance.value?.getSelection();
    if (range) {
      quillInstance.value.insertText(range.index, text);
    }
  },
});
</script>

<style scoped>
.editor-wrapper {
  position: relative;
  transition: height 0.3s ease;
}

.word-counter {
  position: absolute;
  bottom: 15px;
  right: 25px;
  color: #666;
  font-size: 12px;
  background: rgba(255, 255, 255, 0.9);
  padding: 4px 8px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 全屏时，把最外层 div 拉满屏幕 */
.fullscreen-editor {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  background: white;
  padding: 20px;
  box-sizing: border-box;
}

/* Quill 会给 toolbar 里的按钮加一个 .ql-fullscreen 类名，我们不需要额外再设位置 */
/* 如果想自定义图标大小、hover 效果，可以在这里写： */
/*
.ql-fullscreen {
  width: 24px;
  height: 24px;
}
.ql-fullscreen:hover {
  background-color: #f0f0f0;
}
*/

.ql-editor {
  overflow-y: auto;
  line-height: 1.6;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, sans-serif;
}

.ql-container {
  border-radius: 0 0 8px 8px;
}
</style>
